package com.ding.easycontroller.socket;

import com.ding.easycontroller.service.WebSocketService;
import com.ding.easycontroller.work.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.net.URI;

@Component
public class DispatcherWebSocketHandler implements WebSocketHandler {

    @Autowired
    private WebSocketService webSocketService;

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        URI uri = webSocketSession.getUri();
        WebSocket webSocket = webSocketService.matchesWebSocket(getPath(uri));
        if (webSocket != null) {
            webSocket.handleOpen(webSocketSession);
        }
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        URI uri = webSocketSession.getUri();
        WebSocket webSocket = webSocketService.matchesWebSocket(getPath(uri));
        if (webSocket != null) {//负载可以为别的?
            String msg = (String) webSocketMessage.getPayload();
            webSocket.handleMessage(webSocketSession, msg);
        }

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        //简单打印
        throwable.printStackTrace();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        //当连接关闭
        URI uri = webSocketSession.getUri();
        WebSocket webSocket = webSocketService.matchesWebSocket(getPath(uri));
        if (webSocket != null) {
            webSocket.handleClose(webSocketSession, closeStatus);
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }


    @Value("${websocket.basePath:/socket/}")
    private String base;

    private String getPath(URI uri) {
        String path = uri.getPath();
        return path.substring(7);
    }


}
